// 导入需要的库和模块
import PropTypes from 'prop-types'; // 用于类型检查
import { useEffect, useState } from 'react'; // 从react中导入hooks

// material-ui相关的组件和hooks
import { useTheme } from '@mui/material/styles'; // 用于获取当前主题
import Box from '@mui/material/Box'; // 布局组件
import MuiAccordion from '@mui/material/Accordion'; // 手风琴组件
import MuiAccordionDetails from '@mui/material/AccordionDetails'; // 手风琴详细内容组件
import MuiAccordionSummary from '@mui/material/AccordionSummary'; // 手风琴摘要组件

// 导入资源
import ExpandMoreIcon from '@mui/icons-material/ExpandMore'; // 手风琴展开图标

// 手风琴组件定义
const Accordion = ({ data, defaultExpandedId = null, expandIcon, square, toggle }) => {
  const theme = useTheme(); // 使用主题hook获取当前主题

  // 定义一个状态变量来跟踪哪个手风琴项是展开的
  const [expanded, setExpanded] = useState(null);

  // 定义一个函数来处理手风琴项的展开和折叠
  const handleChange = (panel) => (event, newExpanded) => {
    if (toggle) setExpanded(newExpanded ? panel : false);
  };

  // 当默认展开的手风琴项ID变化时，更新状态
  useEffect(() => {
    setExpanded(defaultExpandedId);
  }, [defaultExpandedId]);

  return (
    <Box sx={{ width: '100%' }}>
      {data &&
        data.map((item) => (
          <MuiAccordion
            key={item.id}
            defaultExpanded={!item.disabled && item.defaultExpand}
            expanded={(!toggle && !item.disabled && item.expanded) || (toggle && expanded === item.id)}
            disabled={item.disabled}
            square={square}
            onChange={handleChange(item.id)}
          >
            <MuiAccordionSummary
              expandIcon={expandIcon || expandIcon === false ? expandIcon : <ExpandMoreIcon />}
              sx={{ color: theme.palette.mode === 'dark' ? 'grey.600' : 'grey.900', fontWeight: 500 }}
            >
              {item.title}
            </MuiAccordionSummary>
            <MuiAccordionDetails>{item.content}</MuiAccordionDetails>
          </MuiAccordion>
        ))}
    </Box>
  );
};

// 对组件的props进行类型检查
Accordion.propTypes = {
  data: PropTypes.array,
  defaultExpandedId: PropTypes.string,
  expandIcon: PropTypes.object,
  square: PropTypes.bool,
  toggle: PropTypes.bool
};

// 导出组件
export default Accordion;
